import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  PageContainer,
  ProTable,
} from '@ant-design/pro-components';
import '@umijs/max';
import {Button, message, Tag} from 'antd';
import React, { useRef, useState } from 'react';
import CreateModal from "@/pages/Teacher/components/CreateModal";
import UpdateModal from "@/pages/Teacher/components/UpdateModal";
import {TableDropdown} from "@ant-design/pro-table";
import { history } from 'umi';
import {
  addTeacherUsingPost,
  deleteTeacherUsingPost, listTeacherByPageUsingGet,
  updateTeacherUsingPost
} from "@/services/backend1/teacherController";

const TableList: React.FC = () => {
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<API.Teacher>();
  const [selectedRowsState, setSelectedRows] = useState<API.Teacher[]>([]);

  /**
   * @en-US Add node
   * @zh-CN 添加节点
   * @param fields
   */
  const handleAdd = async (fields: API.Teacher) => {
    const hide = message.loading('正在添加');
    try {
      await addTeacherUsingPost({
        ...fields,
      });
      hide();
      message.success('创建成功');
      handleModalOpen(false);
      return true;
    } catch (error : any) {
      hide();
      message.error('创建失败!'+ error.message);
      return false;
    }
  };

  /**
   * @en-US Update node
   * @zh-CN 更新节点
   *
   * @param fields
   */
  const handleUpdate = async (fields: API.Teacher) => {
    if (!currentRow) {
      return ;
    }
    const hide = message.loading('修改中');
    try {
      await updateTeacherUsingPost({
        id: currentRow.id,
        ...fields,
      });
      hide();
      message.success('修改成功');
      return true;
    } catch (error : any) {
      hide();
      message.error('修改失败！'+error.message);
      return false;
    }
  };

  /**
   *  Delete node
   * @zh-CN 删除节点
   *
   * @param selectedRows
   */
  const handleRemove = async (record: API.Teacher) => {
    const hide = message.loading('正在删除');
    if (!record) return true;
    try {
      await deleteTeacherUsingPost({
        id: record.id
      });
      hide();
      message.success('删除成功');
      actionRef.current?.reload();
      return true;
    } catch (error: any) {
      hide();
      message.error('删除失败！' + error.message );
      return false;
    }
  };

  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */

  const columns: ProColumns<API.Teacher>[] = [
    {
      title: 'id',
      dataIndex: 'id',
      valueType: 'index',
    },
    {
      title: '名字',
      dataIndex: 'teacher_name',
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
    },
    {
      title: '性别',
      dataIndex: 'teacher_sex',
      hideInSearch: true,
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
    },
    {
      title: '年龄',
      dataIndex: 'teacher_year',
      hideInSearch: true,
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
    },
    {
      title: '增删改查权限',
      dataIndex: 'teacher_quanxian',
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
      valueEnum: {
        "true": {
          text: '允许',
          status: 'Processing',
        },
        "false": {
          text: '拒绝',
          status: 'Error',
        },
      },
    },
    {
      title: '负责班级',
      dataIndex: 'teacher_class',
      hideInSearch: true,
      formItemProps: {
        rules: [{
          required: true,
        }]
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (text, record, _, action) => [
        <Button
          type="text"
          key="config"
          danger
          onClick={() => {
            handleUpdateModalOpen(true);
            setCurrentRow(record);
          }}
        >
          修改
        </Button>,
        <Button
          type="text"
          key="config"
          danger
          onClick={() => {
            handleRemove(record);
          }}
        >
          删除
        </Button>,
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'教师表'}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={async (params: { pageSize?: number; current?: number; keyword?: string }) => {
          const res = await listTeacherByPageUsingGet({
            ...params,
          });
          if (res.data) {
            return {
              data: res.data.records || [],
              success: true,
              total: res.data.total,
            };
          } else {
            return {
              data: [],
              success: false,
              total: 0,
            };
          }
        }}
        columns={columns}
      />
      <UpdateModal
        onSubmit={async (value) => {
          const success = await handleUpdate(value);
          if (success) {
            handleUpdateModalOpen(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalOpen(false);
          if (!showDetail) {
            setCurrentRow(undefined);
          }
        }}
        updateModalOpen={updateModalOpen}
        values={currentRow || {}}
        columns={columns}
      />
      <CreateModal
        columns={columns}
        onCancel={() => {
          handleModalOpen(false);
        }}
        onSubmit={(values) => {
          handleAdd(values);
        }}
        createModalOpen={createModalOpen}
      />
    </PageContainer>
  );
};
export default TableList;
